﻿using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Threading;
using Automator.Classes;
using Automator.Runtime.Classes;
using Microsoft.Win32;

namespace Automator.Windows
{    
    public partial class OpenWindow : Window
    {
        private enum SqlSelectResultType { OK, Empty, Error };        
        
        private DocumentTypes _docType;
        private BackgroundWorker _worker = new BackgroundWorker();
        private SqlSelectResultType _resultType = SqlSelectResultType.OK;
        private DispatcherTimer _timer = new DispatcherTimer();
        
        public OpenWindow(DocumentTypes docType)
        {
            InitializeComponent();
            
            this._docType = docType;
            this.Title = String.Format("Open {0}", _docType.ToString());
            _worker.WorkerReportsProgress = false;
            _worker.WorkerSupportsCancellation = false;
            _worker.DoWork += new DoWorkEventHandler(_worker_DoWork);
            _worker.RunWorkerCompleted +=
                delegate(object sender, RunWorkerCompletedEventArgs e) { gridEntities.ItemsSource = e.Result as DataView; };
            
            _timer.Interval = new TimeSpan(0,0,1);
            _timer.Tick += delegate(object sender, EventArgs e)
            {
                _timer.Stop();
                if (gridEntities.ItemsSource != null)
                {
                    DataView dv = gridEntities.ItemsSource as DataView;
                    dv.RowFilter = (String.IsNullOrEmpty(edtFilter.Text))
                        ? String.Empty
                        : String.Format("Name like '{0}%'", edtFilter.Text);
                }
            };
        }
        
        private void BtnOpen_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            switch (this._docType)
            {
                case DocumentTypes.Workflow:
                    dialog.DefaultExt = ".xml";
                    dialog.Filter = "Automator Workflow Files (*.xml)|*.xml";
                    break;
                case DocumentTypes.Solution:
                    dialog.DefaultExt = ".autosln";
                    dialog.Filter = "Automator Solution Files (*.autosln)|*.autosln";
                    break;
            }
            
            dialog.Title = String.Format("Open {0}", _docType.ToString());
            dialog.CheckPathExists = true;
            dialog.DereferenceLinks = true;
            dialog.Multiselect = false;
            dialog.ValidateNames = true;
            if (dialog.ShowDialog(this).Value)
            {
                if (!rbFileSystem.IsChecked.Value)
                {
                    rbFileSystem.IsChecked = true;
                    RbFileSystem_Click(null, new RoutedEventArgs());
                }
                edtFileName.Text = dialog.FileName;
                if (!rbDatabase.IsEnabled)
                    BtnOk_Click(null, new RoutedEventArgs());
            }
            else
                if (!rbDatabase.IsEnabled)
                {
                    this.DialogResult = false;
                    Close();
                }
        }
        
        private void RbFileSystem_Click(object sender, RoutedEventArgs e)
        {
            edtFileName.IsEnabled = rbFileSystem.IsChecked.Value;
            gridEntities.IsEnabled = rbDatabase.IsChecked.Value;
            edtFilter.IsEnabled = rbDatabase.IsChecked.Value;
        }
        
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (Automator.Runtime.Settings.SqlConnectionString == null)
                rbDatabase.IsEnabled = false;
            else
            {
                rbDatabase.IsChecked = true;
                _worker.RunWorkerAsync(_docType);
            }
            RbFileSystem_Click(null, new RoutedEventArgs());
            if (!rbDatabase.IsEnabled)
                BtnOpen_Click(null, new RoutedEventArgs());
        }

        private void _worker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                e.Result = DataAccess.Select(e.Argument.ToString());
                if ((e.Result as DataView).Count > 0)
                    _resultType = SqlSelectResultType.OK;                    
                else
                {
                    e.Result = DataAccess.GetEmptyView();
                    _resultType = SqlSelectResultType.Empty;
                }
            }
            catch (Exception ex)
            {
                e.Result = DataAccess.GetErrorView(ex.Message);
                _resultType = SqlSelectResultType.Error;
            }
        }
        
        private void BtnOk_Click(object sender, RoutedEventArgs e)
        {
            if ((rbFileSystem.IsChecked.Value && !String.IsNullOrEmpty(edtFileName.Text)) ||
                (rbDatabase.IsChecked.Value && gridEntities.SelectedItem != null && _resultType == SqlSelectResultType.OK))
            {
                this.DialogResult = true;
                Close();
            }
        }
        
        private void GridEntities_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                BtnOk_Click(null, new RoutedEventArgs());
            }
        }
        
        private void EdtFilter_TextChanged(object sender, TextChangedEventArgs e)
        {
            _timer.Start();
        }
        
        private void BtnDeleteDocument_Click(object sender, RoutedEventArgs e)
        {
            if (Microsoft.Windows.Controls.MessageBox.Show(
                this, "Delete this document from database? This operation cannot be reverted!", "Confirmation",
                MessageBoxButton.YesNo, MessageBoxImage.Question
               ) == MessageBoxResult.Yes)
            {
                Guid _id = Guid.Parse((sender as Button).Tag.ToString());
                try
                {
                    DataAccess.Delete(_id);
                    _worker.RunWorkerAsync(_docType);
                }
                catch (Exception ex)
                {
                    Microsoft.Windows.Controls.MessageBox.Show(this, ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
    }
}